from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Optional,List

# 责任链所要处理的类
class ChainHandler:
    name: str = ''
    score: int = 100
    def __init__(self, name: str, score: int):
        self.name = name
        self.score = score

## 责任链接口
class Chain(ABC):

    def __init__(self, name: str):
        self.name = name
        self.nextChain: List[Optional[Chain]] = []

    def main_flow(self, request: ChainHandler):
        print(f"{self.name}开始处理")
        result = self.handle(request)
        print(f"{self.name}处理结束")
        self.pass_to_next(request, result)

    @abstractmethod
    def handle(self, request: ChainHandler) -> int:
        pass

    def set_next(self, chain: Chain):
        self.nextChain.append(chain)

    
    def pass_to_next(self, request: ChainHandler, method: int) -> None:
        if len(self.nextChain) == 0:
            print(f"{self.name}没有下一个处理者")
            return
        if len(self.nextChain) == 1:
            self.nextChain[0].main_flow(request)
            return
        if method == 0:
            self.nextChain[0].main_flow(request)
        elif method == 1:
            self.nextChain[1].main_flow(request)
        else:
            for r in self.nextChain:
                r.main_flow(request)

# 责任链1
class ChainFirst(Chain):
    def handle(self, request: ChainHandler) -> int:
        if request.score > 60:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩及格，进入下一个处理者")
            return 1
        else:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩不及格，结束处理")
            return 0

# 责任链2
class ChainSecond(Chain):
    def handle(self, request: ChainHandler) -> None:
        if request.score > 80:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩良好，进入下一个处理者")
            return 1
        else:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩中等，结束处理")
            return 0

# 责任链3
class ChainThird(Chain):
    def handle(self, request: ChainHandler) -> None:
        if request.score > 90:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩优秀，结束处理")
            return 1
        else:
            print(f"{self.name}开启处理请求, {request.name}得分：{request.score}成绩良好，结束处理")
            return 0
    
if __name__ == "__main__":
    one = ChainFirst("ChainFirst")
    two = ChainSecond("ChainSecond")
    three = ChainThird("ChainThird")
    one.set_next(two)
    two.set_next(three)
    one.main_flow(ChainHandler("alex", 91))